package com.ruoyi.utils;

import com.ruoyi.common.entity.StorageConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;


/**
 * 解密工具类，用于解密前端加密的敏感信息
 */
@Component
public class DecryptUtil {


    private final String secretKey="dougongshe123456";
    
    // 与前端保持一致的初始化向量
    private static final String IV = "InitVector16Byte";
    
    /**
     * AES解密
     */
    public String decrypt(String encryptedData) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
        
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        
        return new String(decryptedBytes);
    }
    
    /**
     * 解密存储配置中的敏感信息
     */
    public StorageConfig decryptStorageConfig(StorageConfig config) throws Exception {
        if (config == null) {
            return null;
        }
        
        if (config.getAccessKey() != null && !config.getAccessKey().isEmpty()) {
            config.setAccessKey(decrypt(config.getAccessKey()));
        }
        
        if (config.getSecretKey() != null && !config.getSecretKey().isEmpty()) {
            config.setSecretKey(decrypt(config.getSecretKey()));
        }
        
        if (config.getEndpoint() != null && !config.getEndpoint().isEmpty()) {
            config.setEndpoint(decrypt(config.getEndpoint()));
        }
        
        if (config.getBucketName() != null && !config.getBucketName().isEmpty()) {
            config.setBucketName(decrypt(config.getBucketName()));
        }
        
        if (config.getDomain() != null && !config.getDomain().isEmpty()) {
            config.setDomain(decrypt(config.getDomain()));
        }
        
        if (config.getRegion() != null && !config.getRegion().isEmpty()) {
            config.setRegion(decrypt(config.getRegion()));
        }
        
        return config;
    }
}
